<template>
    <el-dialog 
      v-model="dialogVisible" 
      :title="`编辑用户 - ${formData.UserName}`" 
      width="600px"
      :before-close="handleClose"
    >
      <el-form 
        ref="formRef" 
        :model="formData" 
        label-width="100px" 
        :rules="formRules"
      >
        <!-- 主表字段 -->
        <!-- <el-form-item label="用户ID" prop="userId">
          <el-input v-model="formData.userId" disabled />
        </el-form-item> -->
        
        <el-form-item label="用户名" prop="UserName">
          <el-input v-model="formData.UserName" />
        </el-form-item>
        
        <el-form-item label="密码" prop="Password">
          <el-input v-model="formData.Password" type="password" />
        </el-form-item>
        
        <!-- <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item> -->
        
        <!-- 详情表字段 -->
        <el-form-item label="真实姓名" prop="RealName">
          <el-input v-model="formData.RealName" />
        </el-form-item>
        
        <!-- <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item> -->
        <el-form-item label="用户秘钥" prop="UserKey">
          <el-input v-model="formData.UserKey" disabled/>
        </el-form-item>
        <el-form-item label="秘钥有效期" prop="ExpiryDate">
          <el-input v-model="formData.ExpiryDate"/>
        </el-form-item>
        <!-- <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" type="textarea" :rows="2" />
        </el-form-item> -->
        
        <!-- <el-form-item label="部门" prop="departmentId">
          <el-select 
            v-model="formData.departmentId" 
            placeholder="请选择部门"
            filterable
          >
            <el-option 
              v-for="dept in departments" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id" 
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, reactive, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  
//   const props = defineProps({
//     // 部门数据（从父组件传入）
//     departments: {
//       type: Array,
//       default: () => []
//     }
//   })
  
  const emit = defineEmits(['success'])
  
  const dialogVisible = ref(false)
  const formRef = ref(null)
  const currentUserId = ref(null)
  
  // 表单数据（包含两个表的字段）
  const formData = reactive({
    UserId: '',
    UserName: '',
    RealName: '',
    UserKey: '',
    ExpiryDate: '',
    // departmentId: null
  })
  
  // 表单验证规则 
  const formRules = reactive({
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    // email: [
    //   { required: true, message: '请输入邮箱', trigger: 'blur' },
    //   { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    // ],
    fullName: [
      { required: true, message: '请输入姓名', trigger: 'blur' }
    ]
  })
  
  // 打开弹窗并加载数据 
  const openDialog = async (userId) => {
    // currentUserId.value = userId
    // dialogVisible.value = true
    
      try {
        console.log("前置数据")
      // 加载用户数据（包含两个表的信息）
        const response = await axios.get(`https://localhost:5005/api/user/list/${userId}`)
        console.log("后置数据")
          Object.assign(formData, response.data.user)
          dialogVisible.value = true
    } catch (error) {
      ElMessage.error('加载用户数据失败')
      console.error(error)
    }
  }
  
  // 提交表单 
  const submitForm = async () => {
    // 验证表单
    if (!await formRef.value.validate()) return
    
      try {
        console.log("提交数据前", formData)
      // 调用更新API 
      const response = await axios.post(`https://localhost:5005/api/user/update/${formData.UserId}`, formData)
      console.log("提交数据", formData)
      
      if (response.data.Success) {
        ElMessage.success('用户信息更新成功')
        dialogVisible.value = false
        emit('success') // 通知父组件刷新数据
      } else {
        ElMessage.error(`更新失败: ${response.data.Message}`)
      }
    } catch (error) {
      ElMessage.error('更新请求失败')
      console.error(error)
    }
  }
  
  // 关闭弹窗前确认
  const handleClose = (done) => {
    // 检查表单是否有修改
    const isDirty = Object.values(formData).some(value => value !== '')
    
    if (isDirty) {
      ElMessageBox.confirm('确定要放弃修改吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done()
      })
    } else {
      done()
    }
  }
  
  // 暴露open方法给父组件 
  defineExpose({ openDialog })
  </script>
  